package com.forezp.configclient.rabbitMq;

import com.rabbitmq.client.*;
import org.springframework.amqp.rabbit.listener.BlockingQueueConsumer;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @version V1.0  </br>
 * @ClassName Recv </br>
 * @Description TODO  </br>
 * @Author tonywang</br>
 * @DATE 11/22/2018 5:51 PM</br>
 */
public class Recv {
    private final static String QUEUE_NAME = "hello";
    public static void main(String[] args) throws IOException, TimeoutException {
        //打开连接和创建频道，与发送端一样
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setUsername("root");
        factory.setPassword("root");
        factory.setVirtualHost("/");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //声明队列，主要为了防止消息接收者先运行此程序，队列还不存在时创建队列。
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
        //创建队列消费者
        DefaultConsumer consumer =new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                 super.handleDelivery(consumerTag, envelope, properties, body);
                 String msg=new String(body,"UTF-8");
                 System.out.println("Received consumerTag is:"+consumerTag);
                 System.out.println("Received Envelope is:" + envelope);
                 System.out.println("Received properties is:" + properties);
                 System.out.println("Received message is:"+msg);
            }
        };
        boolean ack = false ; //打开应答机制

        //指定消费队列
        channel.basicConsume(QUEUE_NAME,ack,consumer);

    }

}
